package com.hunttown.mes.manage.controller._iot;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.IotTimedTasksManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.TransportOperateLogManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.IotTimedTasksDTO;
import com.hunttown.mes.rpc.domain.enums.iot.tasks.TaskFailTacticEnum;
import com.hunttown.mes.rpc.domain.enums.iot.tasks.TaskStatusEnum;
import com.hunttown.mes.rpc.domain.enums.iot.tasks.TaskTypeEnum;
import com.hunttown.mes.rpc.domain.query.IotTimedTasksDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import org.apache.logging.log4j.core.util.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 定时任务
 * @author: wangjunfu
 * @date: 2020年10月13日 11:10
 * @description:
 */
@Controller
@RequestMapping(value = "/iot/timed-tasks")
public class TimedTasksController {

    private final static Logger logger = LoggerFactory.getLogger(TimedTasksController.class);

    private final IotTimedTasksManageService iotTimedTasksService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;
    private final TransportOperateLogManageService logService;

    @Autowired
    public TimedTasksController(IotTimedTasksManageService iotTimedTasksService, AnalysisManageManageService manageService, ModelService modelService, TransportOperateLogManageService logService) {
        this.iotTimedTasksService = iotTimedTasksService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.logService = logService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, IotTimedTasksDTOQuery dtoQuery) {

        dtoQuery.setOrderBy("order by id desc");
        Page<IotTimedTasksDTO> dataPage = iotTimedTasksService.getForPage(dtoQuery);

        for (IotTimedTasksDTO item : dataPage.getItems()) {
            //任务类型
            item.setTaskTypeName(TaskTypeEnum.getEnumByKey(item.getTaskType()));

            //任务状态
            item.setStatusName(TaskStatusEnum.getEnumByKey(item.getStatus()));

            //失败策略
            item.setFailTacticName(TaskFailTacticEnum.getEnumByKey(item.getFailTactic()));

            //item.setAreaName(modelService.getIotRegionName(item.getAreaId()));
            //item.setUserName(modelService.getUserTrueName(item.getUserId()));
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        model.addAttribute("taskTypeList", TaskTypeEnum.getEnumList());

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        String[] menus = {"D-Z-RWXX-BJ", "D-Z-RWXX-SC", "D-P-RWXX-QDTZ"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "iot/timed-tasks/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        IotTimedTasksDTO obj;

        if (id > 0) {
            obj = iotTimedTasksService.getById(id);
        } else {
            obj = new IotTimedTasksDTO();
            obj.setId(0);
            obj.setRetryTimes(1);
            obj.setOperateType(-1);
        }
        model.addAttribute("Obj", obj);

        modelService.getIotRegionPage(model);
        modelService.getUserPage(model);
        model.addAttribute("taskTypeList", TaskTypeEnum.getEnumList());
        model.addAttribute("taskStatusList", TaskStatusEnum.getEnumList());
        model.addAttribute("taskFailTacticList", TaskFailTacticEnum.getEnumList());

        return "iot/timed-tasks/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, IotTimedTasksDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            //日期
            objDTO.setStartDate(DateConvertUtils.strToDate(objDTO.getStartDateSr()));
            objDTO.setEndDate(DateConvertUtils.strToDate(objDTO.getEndDateSr()));
            objDTO.setBeginTime(DateConvertUtils.strToDate("1990-01-01 " + objDTO.getBeginTimeSr()));
            objDTO.setEndTime(DateConvertUtils.strToDate("1990-01-01 " + objDTO.getEndTimeSr()));

            //拼接CRON表达式，格式: [秒]  [分]  [小时]  [日]  [月]  [周]  [年]
            StringBuilder sb = new StringBuilder();
            sb.append(objDTO.getCronSecond() + " ");
            sb.append(objDTO.getCronMinute() + " ");
            sb.append(objDTO.getCronHour() + " ");
            sb.append(objDTO.getCronDay() + " ");
            sb.append(objDTO.getCronMonth() + " ");
            sb.append(objDTO.getCronWeek() + " ");
            sb.append(objDTO.getCronYear());

            objDTO.setExecuteTactic(sb.toString());

            //验证CRON表达式是否正确
            if (!CronExpression.isValidExpression(objDTO.getExecuteTactic())) {
                map = OperateCode.CompositionResult(map, -10, "CRON执行规则不正确！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            //单选
            if (objDTO.getIsSystem() == null) {
                objDTO.setIsSystem(0);
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setIsExecuteOnce(0);
                objDTO.setResult(0);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = iotTimedTasksService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = iotTimedTasksService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 135, objDTO.getId(), 2,
                    "更新定时任务信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = iotTimedTasksService.delete(id);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 135, id, 4,
                    "删除定时任务信息",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = iotTimedTasksService.changeState(id, status);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 135, id == null ? 0 : id, 2,
                    "更新定时任务状态",
                    "记录状态更新" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        IotTimedTasksDTO obj = new IotTimedTasksDTO();
        obj.setId(id);

        if (id > 0) {
            obj = iotTimedTasksService.getById(id);
        }
        iotTimedTasksService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

    //region 启动停止任务

    /**
     * 启动停止任务
     *
     * @param id     任务ID
     * @param status 1启动 2停止
     * @return map
     */
    @RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
    @ResponseBody
    public String changeStatus(HttpServletRequest request, Integer id, Integer status) {

        String result = "";
        Map<String, String> map = new HashMap<String, String>();
        map.put("returnCode", "0");

        String msg = "任务启动";
        if (status == 2) {
            msg = "任务停止";
        }

        try {
            Boolean isNext = iotTimedTasksService.changeStatus(id, status);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 135, id, 4,
                    "定时任务启停记录",
                    msg + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion
}
